package com.googlecode.strutson.utils

import java.util.zip.ZipEntry
import java.util.zip.ZipFile
import org.apache.commons.io.IOUtils

/**
 * Unzips a file
 */
class ZipUtils {
    static void unzipArchive(File archive, File outputDir, String appName) {
        try {
            def zipfile = new ZipFile(archive);
            print "Extracting files: "
            zipfile.entries().eachWithIndex {entry, i ->
                unzipEntry(zipfile, entry, outputDir);
                print '#'
            }
            println "[done]"
        } catch (Exception e) {
            println e.message
            return;
        }
    }

    static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException {

        if (entry.isDirectory()) {
            createDir(new File(outputDir, entry.getName()))
            return;
        }

        def outputFile = new File(outputDir, entry.getName())
        if (!outputFile.getParentFile().exists()) {
            createDir(outputFile.getParentFile())
        }

        def inputStream = new BufferedInputStream(zipfile.getInputStream(entry))
        def outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))

        try {
            IOUtils.copy(inputStream, outputStream)
        } finally {
            outputStream.close()
            inputStream.close()
        }
    }

    private static void createDir(File dir) {
        if (!dir.mkdirs()) throw new RuntimeException("Can not create dir ${dir}")
    }
}